package yuan.common;

import com.alibaba.fastjson.JSONObject;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramGauges;

import java.time.Duration;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class MyTimer {

    static Timer timer = Timer.builder("a_test_timer")
                .tag("ServiceCode", "PS10023").publishPercentileHistogram().publishPercentiles(.1, .2, .3, .4, .5, .6, .7, .8, .9, 1)
                .description("timer sample test.")
                .register(Metrics.globalRegistry);


    public static String testTimerSample(){

//        for(int i=0; i<2; i++) {
            timer.record(() -> {
                try {
                    Random r = new Random();
                    TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
                } catch (InterruptedException e){
                    e.printStackTrace();
                }

            });
//        }

        System.out.println(timer.count());
        System.out.println(timer.measure());
        System.out.println(timer.totalTime(TimeUnit.SECONDS));
        System.out.println(timer.mean(TimeUnit.SECONDS));
        System.out.println(timer.max(TimeUnit.SECONDS));

        return JSONObject.toJSONString(timer.measure());
    }

}
